package cn.itcast.redisdemo.web;

import cn.hutool.json.JSONUtil;
import cn.itcast.redisdemo.pojo.UserDO;
import cn.itcast.redisdemo.utils.CacheRebuildUtils;
import cn.itcast.redisdemo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/redis")
@Slf4j
public class RedisTestController {
    
    @Resource
    RedisUtil redisUtil;
    
    @Resource
    CacheRebuildUtils cacheRebuildUtils;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    RedissonClient redissonClient;

    @GetMapping("/test")
    private String test11(){

        redisUtil.set("user:111", JSONUtil.toJsonStr(UserDO.builder().id(1).name("ddd").age(11).build()));
        return "1";
    }
    public void testHashPutAll(){
        RLock lock = redissonClient.getLock("ddd");
        boolean b = lock.tryLock();
        if (b){
            try {
                System.out.println(1);
            } finally {
                lock.unlock();
            }
        }
    }
    
    @GetMapping("/allRedis")
    public void test(){
        redisUtil.set("StrKey","dddd");
        
        redisUtil.hPut("hashKey","name","szh");
        
        redisUtil.lLeftPush("listKey","name");
        
        redisUtil.sAdd("setKey","sssss");
        System.out.println("ok");
    }
    
    @GetMapping("/hYSize")
    public Long testHy(){
        Long aLong = redisUtil.hYSize("szh");
        System.out.println(aLong);
        return aLong;
    }
    @GetMapping("/hyadd")
    public Long hyadd(){
        Long aLong = redisUtil.hYAdd("szh","dddd","ddd","www");
        System.out.println(aLong);
        return aLong;
    }
    
    private final static String CACHE_BREAK_DOWN ="cacheBreakDown";
    private final static String rebuild_CACHE_BREAK_DOWN ="rebuild_cacheBreakDown";
    // 演示，缓存击穿-解决方式2：逻辑过期处理。
    
    // 重建热点key
    public void rebuildKey(Long id){
        UserDO userDO = cacheRebuildUtils.queryHotSpotCacheData(CACHE_BREAK_DOWN, id, UserDO.class, this::getUser);
        // 重新放入redis中
    }
    public UserDO getUser(Long id){
        return new UserDO();
    }
}
